import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_menu/biz/order/detail/detail_controller.dart';
import 'package:flutter_menu/biz/order/order_controller.dart';
import 'package:flutter_menu/biz/order/record/shop_car_controller.dart';
import 'package:flutter_menu/data/provider/formula_provider.dart';
import 'package:flutter_menu/data/provider/product_provider.dart';
import 'package:flutter_menu/model/meal_spec_model.dart';
import 'package:flutter_menu/model/menu_model.dart';
import 'package:flutter_menu/model/product_model.dart';
import 'package:get/get.dart';

const String othersKey = "";

class OptionsController extends GetxController {
  static const String idSpecWidget = "specWidget";
  static const String idSpecDialog = "specDialog";

  static OptionsController get to => Get.find();

  ProductProvider productProvider = Get.find<ProductProvider>();
  FormulaProvider formulaProvider = Get.find<FormulaProvider>();
  DetailController detailController = DetailController.to;

  // 规格详情列表
  final Rx<List<Spec>> specWithOptions = Rx<List<Spec>>([]);

  // 以选规格
  String selectedSpecId = "";

  // 菜品 的选项组： key为规格选项组， value为选项列表（分类选项组为多选一，其他选项组为多选多）
  Map<String, List<SelectedOption>> selectedOptionsByGroup = {};

  // 套餐 的选项组
  List<SelectedPackageGroup> selectedPackageGroups = [];

  final Rx<List<Group>> groupWithFoods = Rx<List<Group>>([]);

  final RxInt remainingOfProduct = 0.obs;

  late ProductModel productDetail;

  final TextEditingController remarkController = TextEditingController();

  @override
  void onInit() {
    super.onInit();

    // 初始化菜品数量
    setProductQuantity(detailController.selectedProductNumber.value);

    // 初始化规格和选项
    initSpecFromShopCar();

    if (detailController.isPackage()) {
      // 获取套餐的分组-菜品
      getFoodsInPackage();
    } else {
      // 获取菜品的规格-选项
      getSpecList();
    }
  }

  /// 从购物车中获取规格和选项
  void initSpecFromShopCar() {
    var productUuid = detailController.productUuid;
    var shopCarItem =
        ShopCarController.to.getShopCarItemByProductId(productUuid);

    var productSpecsUuid = shopCarItem?.first?.spec?.productSpecsUuid;
    if (productSpecsUuid != null) {
      updateSelectedSpecId(productSpecsUuid);
    }

    var optionList = shopCarItem?.first?.optionList;
    if (optionList != null && optionList.isNotEmpty) {
      for (var item in optionList) {
        var option = item.spec;

        var isGroup = option.isGroupOption();
        String groupId = (isGroup) ? option.optionsGroupName! : othersKey;

        updateOptionQuantity(groupId, item.id,
            quantity: item.count, specOption: item.spec);
      }
    }
  }

  void getSpecList() {
    // 自定义菜单中的规格列表
    var specListInCustomMenu = detailController.dishList;

    // 菜品的Uuid
    var productUuid = detailController.productUuid;
    debugPrint("specListInCustomMenu: $specListInCustomMenu $productUuid");

    // get options for specList
    // 通过productUuid去productList表中查询菜品详情
    if (productUuid.isNotEmpty) {
      productProvider.getProductByIdAsync(productUuid).then((value) {
        if (value != null) {
          productDetail = value;

          var specListInSku = value.specs;

          //合并自定义菜单和SKU列表中的规格列表
          specWithOptions.value = specListInCustomMenu
              .map((item) {
                var specsUuid = item.productSpecsUuid;
                var filteredSpecDetail = specListInSku.firstWhereOrNull((spec) {
                  return spec.id == specsUuid;
                });

                // 停售的规格不显示
                if (filteredSpecDetail?.isStopSpec() ?? true) {
                  return null;
                }

                return filteredSpecDetail;
              })
              .whereType<Spec>()
              .toList();

          update([idSpecDialog]);

          // 规格默认勾选选项 (TODO 计算沽清数量时，若默认规格售罄，则默认其他规格为【已选择状态】)
          if (selectedSpecId.isEmpty) {
            var defaultSpecItem =
                specWithOptions.value.firstWhereOrNull((item) {
              return item.isDefaultSpec();
            });
            if (defaultSpecItem != null) {
              updateSelectedSpecId(defaultSpecItem.id ?? "");
            }
          }
        }
      });
    }
  }

  //更新选中规格
  void updateSelectedSpecId(String id) {
    debugPrint("updateSelectedSpecId $id");
    if (selectedSpecId != id) {
      selectedSpecId = id;
      update([idSpecDialog]);
    }
  }

  Spec? getSelectedSpecModel() {
    return specWithOptions.value.firstWhereOrNull((item) {
      return item.id == selectedSpecId;
    });
  }

  List<SpecOption> getOptionListBySelectedSpecId() {
    var selectedSpecItem = specWithOptions.value.firstWhereOrNull((item) {
      return item.id == selectedSpecId;
    });
    return (selectedSpecItem?.options) ?? [];
  }

  List<MapEntry<String, List<SpecOption>>> getOptionListByGroup(
      List<SpecOption> optionList) {
    debugPrint("getOptionsByGroup $optionList");
    Map<String, List<SpecOption>> groupedItems = {};

    for (var item in optionList) {
      // 按GroupName分组
      // 如果 categoryName 为空，则将其归类为 "Other"
      var isGroup = item.isGroupOption();
      String groupId = (isGroup) ? item.optionsGroupName! : othersKey;

      if (groupedItems.containsKey(groupId)) {
        groupedItems[groupId]!.add(item);
      } else {
        groupedItems[groupId] = [item];
      }

      // 把个分组中的默认值筛选出来
      if (selectedOptionsByGroup.isEmpty) {
        String? id;
        var quantity = 1;
        if (isGroup) {
          var options = item.options;
          var defaultOptionInGroup = options.firstWhereOrNull((item) {
            return item.isDefaultOption();
          });
          id = defaultOptionInGroup?.id;
        } else if (item.isDefaultOption()) {
          id = item.id;
        }
        updateOptionQuantity(groupId, id, quantity: quantity, specOption: item);
      }
    }

    // 将 "Other" 组放在最后
    return groupedItems.entries.toList()
      ..sort((a, b) => a.key == othersKey ? 1 : 0);
  }

  void updateOptionQuantity(String? groupId, String? optionId,
      {int quantity = 1, SpecOption? specOption}) {
    updateOptionQuantityByGroup(
        selectedOptionsByGroup, groupId, optionId, specOption,
        quantity: quantity);
  }

  /// 普通Group 多选一
  ///  Others Group 多选多
  void updateOptionQuantityByGroup(
      Map<String, List<SelectedOption>> selectedOptionsByGroup,
      String? groupId,
      String? optionId,
      SpecOption? specOption,
      {int quantity = 1}) {
    debugPrint("updateOptionQuantity: $groupId; $optionId; $quantity");

    if (optionId == null ||
        optionId.isEmpty ||
        groupId == null ||
        specOption == null) return;

    if (!selectedOptionsByGroup.containsKey(groupId)) {
      selectedOptionsByGroup[groupId] = [];
    }

    bool isOtherMode = groupId.isEmpty;
    if (!isOtherMode) {
      selectedOptionsByGroup[groupId] = [];
    }

    // 查找选项是否已存在
    var existingOption = selectedOptionsByGroup[groupId]!
        .firstWhereOrNull((option) => option.id == optionId);

    if (existingOption != null) {
      // 如果已存在，更新数量
      if (isOtherMode) {
        existingOption.quantity += quantity;
      } else {
        existingOption.quantity = quantity;
      }
    } else {
      // 如果不存在，添加新选项
      selectedOptionsByGroup[groupId]!
          .add(SelectedOption(optionId, specOption, quantity));
      // debugPrint("selectedOptionsByGroup: ${selectedOptionsByGroup[groupId]}");
    }

    // 刷新对应group的widget
    update([groupId]);
  }

  // Others Group中移除单个选项
  void removeOptionQuantity(String? groupId, String? optionId) {
    debugPrint("removeOptionQuantity: $groupId; $optionId;");

    if (optionId == null || optionId.isEmpty || groupId == null) return;

    if (selectedOptionsByGroup.containsKey(groupId)) {
      var existingOption = selectedOptionsByGroup[groupId]!
          .firstWhereOrNull((option) => option.id == optionId);

      var result = selectedOptionsByGroup[groupId]!.remove(existingOption);

      // 刷新对应group的widget
      if (result) {
        update([groupId]);
      }
    }
  }

  List<SelectedOption>? getSelectedOptionsByGroup(String groupId) {
    return selectedOptionsByGroup[groupId];
  }

  List<SelectedOption> getSelectedOthersOptions() {
    return selectedOptionsByGroup[othersKey] ?? [];
  }

  bool isOptionSelected(String? groupId, String? optionId) {
    if (optionId == null || optionId.isEmpty || groupId == null) return false;
    if (selectedOptionsByGroup.containsKey(groupId)) {
      return selectedOptionsByGroup[groupId]!
          .any((option) => option.id == optionId);
    }
    return false;
  }

  int optionCountForNormalGroup(String? groupId) {
    var initCount = 1;
    if (groupId == null) return initCount;
    if (selectedOptionsByGroup.containsKey(groupId)) {
      return selectedOptionsByGroup[groupId]!.firstOrNull?.quantity ??
          initCount;
    }
    return initCount;
  }

  void updateGroupOptionQuantity(String? groupId, {int quantity = 1}) {
    if (groupId == null) return;
    if (selectedOptionsByGroup.containsKey(groupId)) {
      var selectedOption = selectedOptionsByGroup[groupId]!.firstOrNull;
      if (selectedOption != null) {
        updateOptionQuantity(groupId, selectedOption.id,
            specOption: selectedOption.specOption, quantity: quantity);
      }
    }
  }

  void getFoodsInPackage() {
    // 自定义菜单中的规格列表
    var specListInCustomMenu = detailController.dishList;

    // 菜品的Uuid
    var productUuid = detailController.productUuid;
    debugPrint("specListInCustomMenu: $specListInCustomMenu");

    // 通过productUuid去productList表中查询套餐详情
    if (productUuid.isNotEmpty) {
      productProvider.getProductByIdAsync(productUuid).then((value) {
        if (value != null) {
          groupWithFoods.value = value.groups;
        }
      });
    }
  }

  SelectedPackageGroup? getGroupById(String groupId) {
    return selectedPackageGroups.firstWhereOrNull((item) {
      return item.id == groupId;
    });
  }

  List<SelectedProduct> getSelectedProductByGroupId(String groupId) {
    return getGroupById(groupId)?.productList ?? [];
  }

  void removeProductInGroup(String? groupId, String? productId) {
    debugPrint("removeProductInGroup: $groupId; $productId;");

    if (productId == null || productId.isEmpty || groupId == null) return;

    // 查找指定的 SelectedPackageGroup
    final group = getGroupById(groupId);

    if (group != null) {
      // 在找到的 group 中移除匹配的 productId
      group.productList.removeWhere((dish) => dish.id == productId);

      // 如果该 group 的 dishList 已为空，可选择移除整个 group
      if (group.productList.isEmpty) {
        selectedPackageGroups.removeWhere((g) => g.id == groupId);

        update([groupId]);
      }
    }
  }

  bool isProductExceedLimit(String? groupId, String? productId, int max) {
    if (productId == null || productId.isEmpty || groupId == null) return true;

    // 查找指定的 SelectedPackageGroup
    final group = getGroupById(groupId);

    if (group == null) return false;

    // 在找到的 group 中找到匹配的 productId
    var productList = group.productList;
    var selectedProduct =
        productList.firstWhereOrNull((dish) => dish.id == productId);

    if (selectedProduct != null) {
      return false;
    } else {
      return productList.length >= max;
    }
  }

  var quantity = 1.obs;

  // 根据规格动态计算
  var maxQuantity = 9999;

  void setProductQuantity(int newNumber) {
    if (newNumber <= maxQuantity && newNumber > 0) {
      quantity.value = newNumber;
    }
  }

  void confirmProductOption() {
    var remark = remarkController.text;

    var dishList = detailController.dishList;

    var menuListForProduct = OrderController.to.getMenuListForProduct();
    var skuList = menuListForProduct
        .map((menu) {
          String cMenuId = menu.uuid ?? "";

          var categoryList = menu.categoryList.firstOrNull;
          debugPrint("categoryList: $categoryList");
          if (categoryList == null) {
            return null;
          }

          // 选取的具体规格
          DishList? dish = dishList.firstWhereOrNull(
              (dish) => dish.productSpecsUuid == selectedSpecId);
          if (dish == null) {
            return null;
          }

          //选取的规格所对应的原始选项
          Spec? dishSpec = getSelectedSpecModel();
          if (dishSpec == null) {
            return null;
          }

          // 选取的具体选项组 中的选项
          var specOptionList = selectedOptionsByGroup.values
              .expand((options) => options)
              .map((option) {
            return SpecOptionBox(option.quantity, option.specOption);
          }).toList();

          SKU newSku = SKU(cMenuId, categoryList, productDetail, dish,
              specOptionList, dishSpec);
          return newSku;
        })
        .whereType<SKU>()
        .toList();

    DetailController.to.updateShopItem(ShopCarItem(skuList, remark, quantity.value));
    Get.back();
  }
}

class SelectedPackageGroup {
  final String id;
  final List<SelectedProduct> productList;

  SelectedPackageGroup(this.id, this.productList);
}

class SelectedProduct {
  final String id;
  final String name;
  final int count;
  final String specId;
  final List<SelectedOption> optionList;

  SelectedProduct(this.id, this.name, this.count, this.specId, this.optionList);
}

class SelectedOption {
  final String id;
  int quantity;
  final SpecOption specOption;

  SelectedOption(this.id, this.specOption, this.quantity);

  @override
  String toString() {
    return 'SelectedOption{id: $id, quantity: $quantity}';
  }
}
